import { Dialog } from "@/hoc/Diolog"
import { renderForm } from "@/hoc/renderForm"
import { AddCommdity, CommonOption, EditCommdity, FN, serviceConfig } from "@Tea/model"
import { isSuccessCode, useGloablLoading } from "@Tea/utils"
import { PropType, Ref, defineComponent, ref } from "vue"
import { ElMessage,ElIcon,ElUpload, ElImage,UploadRequestOptions} from "element-plus"
import apiStore from "@/stores/apiStore"
import { Plus } from "@element-plus/icons-vue"
import axios from "axios"
import "./TeaDialog.scss"
import commonClass from "./common.module.scss"

export type TeaTitleType = '新增茶叶' | '编辑茶叶'
export default defineComponent({
  props: {
    visible: {
      type: Object as PropType<Ref<boolean>>,
      required: true
    },
    ruleForm: {
      type: Object as PropType<AddCommdity | EditCommdity>,
      required: true
    },
    title: {
      type: Object as PropType<Ref<TeaTitleType>>,
      required: true
    },
    handleSuccess: {
      type: Object as PropType<FN>,
    },
    teaTypeOptions: {
      type: Object as PropType<Ref<CommonOption[]>>,
      required: true
    }
  },
  setup(props) {
    const { showLoading, closeLoading } = useGloablLoading()
    const { addCommdity, editCommdity } = apiStore().api
    
    const baseUrl = `http://127.0.0.1:${serviceConfig.port}/`

    const curstomHttp = async (option: UploadRequestOptions) => {
      try {
        showLoading()
        const form = new FormData(); // FormData 对象
        form.append("file", option.file); // 文件对象  'upload'是后台接收的参数名
        axios.post('/api/admin/upload', form).then(res => {
          closeLoading()
          if (isSuccessCode(res.data.code)) {
            ElMessage({
              type: "success",
              message:"上传成功！"
            })
            props.ruleForm.cover = res.data.data
          }
        }).catch(e => {

          closeLoading()
        })
        
      } catch (e) {
        console.log(e);
      }
      option.file
    }

    const { Form, resetForm, submitForm } = renderForm<typeof props.ruleForm>({
      ruleForm: props.ruleForm,
      content: [
        [
          {
            span: 24,
            type: "slot",
            label: '封面',
            feild:"cover",
            VNode: () => (
              <ElUpload
                showFileList={false}
                httpRequest={curstomHttp}
              >
                {
                  props.ruleForm.cover ?
                    <ElImage fit="cover" class={`${commonClass.upload_picture}`} src={`${baseUrl}${props.ruleForm.cover}`}></ElImage>
                    : <ElIcon class={`${commonClass.upload_picture} ${commonClass.upload_border}`}><Plus  /></ElIcon>
                }
                
              </ElUpload>
            )
          }
        ],
        [
          {
            span: 12,
            type: "text",
            attr: {
              placeholder:"茶叶名称"
            },
            feild: "teaName",
            label: '茶叶名称'
          },
          {
            span: 12,
            type: "select",
            attr: {
              placeholder:"茶叶类别" 
            },
            option: props.teaTypeOptions,
            feild: "teaType",
            label: '茶叶类别'
          },
        ],
        [
          {
            span: 12,
            type: "text",
            attr: {
              placeholder:"上架数量"
            },
            feild: "number",
            label: '上架数量'
          },
          {
            span: 12,
            type: "text",
            attr: {
              placeholder:"茶叶价格"
            },
            feild: "price",
            label: '茶叶价格'
          }
        ]
      ],
      rules: {
        cover: [
          {
            required: true, message: '请上传封面图片', trigger: 'blur',
          }
        ],
        number: [
          {
            required: true, message: '请输入上架数量', trigger: 'blur',
          }
        ],
        price: [
          {
            required: true, message: '请输入商品单价', trigger: 'blur',
          }
        ],
        teaName:[
          {
            required: true, message: '请输入茶叶名称', trigger: 'blur',
          }
        ],
        teaType:[
          {
            required: true, message: '请选择茶叶类型', trigger: 'blur',
          }
        ],
      }
    })

    // 当校验成功的时候
    const onSuccess = async () => {
      showLoading()
      try {
        const { code, msg } = await (props.title.value === "新增茶叶" ? addCommdity : editCommdity)(props.ruleForm)
        closeLoading()
        if (isSuccessCode(code)) {
          ElMessage({
            message: msg,
            type:'success',
          })
          props.handleSuccess?.()
        }
      } catch (e) {
        closeLoading()
      }
    }
    return () => (
      Dialog({
        visible: props.visible,
        title: props.title.value,
        width: "800px",
        content: Form,
        onConfirm: () => submitForm(onSuccess),
        onClose: () => {
          resetForm()
        }
      })
    )
  }
})